/*
 * @Date         : 2024-05-12 17:44:11 星期0
 * @Author       : xut
 * @Description  :
 */
import grpc from "@grpc/grpc-js"

export const echoServiceImpl = {
  unaryEcho: (call, cb) => {
    let isCancelled = false

    // 当客户调用 cancel() 后，服务端 'cancelled' 事件将被触发
    call.on("cancelled", () => {
      isCancelled = true
      console.log("server received cancelled event")
    })

    // 当客户调用 cancel() 后，服务端 'end'并不会触发，框架内部在 cancelled 事件中主动关闭连接
    call.on("end", () => {
      console.log("server received end event")
      call.end()
    })

    setTimeout(() => {
      if (isCancelled) return
      // 即使继续执行，调用 cb 客户端也无法接收，因为 cancelled 事件后会主动关闭连接
      console.log("server execute")
      const response = { value: "Hello " + call.request.name }
      cb(null, response)
    }, 5000)
  },

  serverStreamingEcho: (call) => {
    let isCancelled = false
    // 当客户调用 cancel() 后，服务端 'cancelled' 事件将被触发
    call.on("cancelled", () => {
      isCancelled = true
      console.log("server received cancelled event")
    })

    // 当客户调用 cancel() 后，服务端 'end'并不会触发，框架内部在 cancelled 事件中主动关闭连接
    call.on("end", () => {
      console.log("server received end event")
      call.end()
    })

    const hello = "Hello From Server"

    for (let i = 0; i < hello.length; i++) {
      if (isCancelled) return
      call.write({ value: hello[i] })
    }

    call.end()
  },
}
